package cn.xiaopengstack.domain.agent.service.execute.flow.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.AutoAgentExecuteResultEntity;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentClientFlowConfigVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientTypyEnumVO;
import cn.xiaopengstack.domain.agent.service.execute.flow.factory.DefaultFlowAgentExecuteStrategyFactory;
import cn.xiaopengstack.domain.agent.service.execute.flow.AbstractExecuteSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Component;

/**
 * @author jiangyangang
 */
@Component("flowMcpToolsAnalysisNode")
@Slf4j
public class Step1McpToolsAnalysisNode extends AbstractExecuteSupport {

    @Override
    protected String doApply(ExecuteCommandEntity requestParameter, DefaultFlowAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("AI Agent 流程式执行策略。开始执行MCP工具分析");
        AiAgentClientFlowConfigVO clientFlowConfigVO = dynamicContext.getAiAgentClientFlowConfigVOMap().get(AiClientTypyEnumVO.TOOL_MCP_CLIENT.getCode());
        String clientId = clientFlowConfigVO.getClientId();
        ChatClient mcpToolsClient = getClientByClientId(clientId);

        String prompt = String.format(clientFlowConfigVO.getStepPrompt(), requestParameter.getMessage());
        String mcpToolResult = mcpToolsClient.prompt()
                .user(prompt)
                .call()
                .content();
        log.info("MCP工具分析结果:{}", mcpToolResult);

        dynamicContext.setStatus(DefaultFlowAgentExecuteStrategyFactory.DynamicContext.ANALYZING_TOOLS);
        dynamicContext.setValue(DefaultFlowAgentExecuteStrategyFactory.DynamicContext.Key.mcpAnalysisResult.name(), mcpToolResult);

        // 发送sse响应
        AutoAgentExecuteResultEntity result = AutoAgentExecuteResultEntity.createAnalysisSubResult(
                dynamicContext.getStep(),
                "analysis_tools",
                mcpToolResult,
                requestParameter.getSessionId());
        sendSseResult(dynamicContext, result);

        dynamicContext.incrStep();

        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<ExecuteCommandEntity, DefaultFlowAgentExecuteStrategyFactory.DynamicContext, String> get(ExecuteCommandEntity requestParameter, DefaultFlowAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return getBean("flowPlanningAnalysisNode");
    }
}
